/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui.usergui;

import bsh.EvalError;
import gui.ExperimentTreeModel;
import gui.JListModelOutputStream;
import gui.ViewerExperimentsModel;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.lang.reflect.InvocationTargetException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.security.auth.login.Configuration;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import stendcontrol.Configurator;
import stendcontrol.DataTract;
import stendcontrol.Experiment;
import stendcontrol.ExperimentContainer;
import stendcontrol.Research;
import stendcontrol.ResearchContainer;
import stendcontrol.ResearchInterpreter;
import stendcontrol.SaveLoadExpContainer;
import stendcontrol.StendLogger;

/**
 *
 * @author minaev
 */
public class MainFrame extends javax.swing.JFrame {

    ExperimentContainer exp_c;
    SaveLoadExpContainer sl_exp_cont;
    ExperimentTreeModel exp_treemodel;
    ResearchContainer research_c;
    DataTract data_tract;
    ResearchInterpreter research_inter;
    LoadFrame load_frame;
    JListModelOutputStream list_outstream;
    ExpsGraphViewer graph_viewer;
    ViewerExperimentsModel viewer_exps;
    ResearchFrame research_frame;
    CalibFrame calib_frame;
    MovingFrame moving_frame;
    ForecastFrame forecast_frame;
    WindowListener graph_viewer_listener = new WindowListener() {
        @Override
        public void windowOpened(WindowEvent e) {
        }

        @Override
        public void windowClosing(WindowEvent e) {
            jmic_graph_viewer.setState(false);
        }

        @Override
        public void windowClosed(WindowEvent e) {
        }

        @Override
        public void windowIconified(WindowEvent e) {
        }

        @Override
        public void windowDeiconified(WindowEvent e) {
        }

        @Override
        public void windowActivated(WindowEvent e) {
        }

        @Override
        public void windowDeactivated(WindowEvent e) {
        }
    };

    /**
     * Creates new form MainFrame
     */
    public MainFrame() {


        load_frame = new LoadFrame();

        setLoad("Чтение конфигурации...", 10);
        Configurator.getConf();

        setLoad("Создание контейнера экспериментов...", 10);
        exp_c = new ExperimentContainer();
        exp_treemodel = new ExperimentTreeModel(exp_c);
        exp_c.addListener(exp_treemodel);

        setLoad("Создание контейнера исследований...", 20);
        research_c = new ResearchContainer();

        setLoad("Заполние контейнера исследований...", 20);
        research_c.loadReseachesFromDirectory();

        setLoad("Создание тракта приема/передачи...", 30);
        data_tract = new DataTract();

        setLoad("Инициализация тракта приема/передачи...", 40);
        data_tract.initDataTract();

        setLoad("Создание интерпретатора исследований...", 50);
        research_inter = new ResearchInterpreter(data_tract);

        setLoad("Создание списка вывода исследования...", 60);
        list_outstream = new JListModelOutputStream();
        research_inter.setSysOut(list_outstream);
        
        setLoad("Инициализация источника экпериментов...", 70);
        sl_exp_cont = new SaveLoadExpContainer();
        sl_exp_cont.init();
        
        setLoad("Создание интерфейса...", 80);
        graph_viewer = new ExpsGraphViewer();
        graph_viewer.addWindowListener(graph_viewer_listener);



        load_frame.dispose();

        initComponents();

        viewer_exps = new ViewerExperimentsModel(exp_c,sl_exp_cont, jTree1,
                graph_viewer.getPlot(), graph_viewer.getLegendsList());

        this.setLocationRelativeTo(null);
    }

    private void setLoad(final String msg, final int procent) {
        try {
            SwingUtilities.invokeAndWait(new Runnable() {
                @Override
                public void run() {
                    load_frame.setLoad(msg, procent);
                }
            });
        } catch (InterruptedException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        } catch (InvocationTargetException ex) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void startResearch() {
        int sel = jl_research.getSelectedIndex();
        if (sel != -1) {
            Experiment cur_exp = genExperiment();
            if (cur_exp != null) {
                if(research_frame!=null){
                    research_frame.dispose();
                    research_frame = null;
                }
                list_outstream.clear();
                exp_c.addExp(cur_exp);
                data_tract.setCurExp(cur_exp);
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        research_frame = new ResearchFrame(data_tract,
                                list_outstream.getListModel());
                        research_frame.setVisible(true);
                    }
                });
                try {
                    research_inter.startResearch(research_c.getResearch(sel));
                } catch (EvalError ex) {
                    StendLogger.log(StendLogger.MSG_ERROR, "Error in syntax "
                            + "research \""
                            + research_c.getResearch(sel).getName()
                            + "\" :" + ex.getMessage());
                    JOptionPane.showMessageDialog(this, "Error in syntax "
                            + "research \""
                            + research_c.getResearch(sel).getName()
                            + "\" :" + ex.getMessage(), "Syntax error",
                            JOptionPane.OK_OPTION);
                }
            }
        }
    }

    private void editResearch() {
        if (jl_research.getSelectedIndex() != -1) {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    new EditResearch(research_c.getResearch(
                            jl_research.getSelectedIndex()), research_c)
                            .setVisible(true);
                }
            });
        }
    }
    
    private void createResearch() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {
                    Research n_res = new Research("no_name", "");
                    research_c.addResearch(n_res);
                    new EditResearch(n_res, research_c)
                            .setVisible(true);
                }
            });
    }

    private Experiment genExperiment() {
        String res = JOptionPane.showInputDialog(this, "Имя эксперимента",
                "Введите имя эксперимента", JOptionPane.OK_CANCEL_OPTION);
        if (res == null) {
            return null;
        } else if (res.equals("")) {
            return null;
        } else {
            return new Experiment(res);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jppm_research = new javax.swing.JPopupMenu();
        jmi_runresearch = new javax.swing.JMenuItem();
        jmi_editresearch = new javax.swing.JMenuItem();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jl_research = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTree1 = new javax.swing.JTree();
        jmain_menu = new javax.swing.JMenuBar();
        jmn_research = new javax.swing.JMenu();
        jmi_create_research = new javax.swing.JMenuItem();
        jmi_start_research = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JPopupMenu.Separator();
        jmi_exit = new javax.swing.JMenuItem();
        jmn_view = new javax.swing.JMenu();
        jmic_graph_viewer = new javax.swing.JCheckBoxMenuItem();
        jmnu_experiment = new javax.swing.JMenu();
        jmi_open_exp = new javax.swing.JMenuItem();
        jmi_save_exp = new javax.swing.JMenuItem();
        jmnu_service = new javax.swing.JMenu();
        jmi_calib_sensors = new javax.swing.JMenuItem();
        jmi_hand_pos = new javax.swing.JMenuItem();
        jmi_forecast = new javax.swing.JMenuItem();

        jmi_runresearch.setText("Запустить");
        jmi_runresearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_runresearchActionPerformed(evt);
            }
        });
        jppm_research.add(jmi_runresearch);

        jmi_editresearch.setText("Редактировать");
        jmi_editresearch.setToolTipText("");
        jmi_editresearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_editresearchActionPerformed(evt);
            }
        });
        jppm_research.add(jmi_editresearch);

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Исследования"));

        jl_research.setModel(research_c.getResearches());
        jl_research.setComponentPopupMenu(jppm_research);
        jScrollPane1.setViewportView(jl_research);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 220, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Эксперименты"));

        jTree1.setModel(exp_treemodel);
        jScrollPane3.setViewportView(jTree1);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                .addContainerGap())
        );

        jmn_research.setText("Исследование");

        jmi_create_research.setText("Создать");
        jmi_create_research.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_create_researchActionPerformed(evt);
            }
        });
        jmn_research.add(jmi_create_research);

        jmi_start_research.setText("Запуск");
        jmi_start_research.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_start_researchActionPerformed(evt);
            }
        });
        jmn_research.add(jmi_start_research);
        jmn_research.add(jSeparator1);

        jmi_exit.setText("Выход");
        jmi_exit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_exitActionPerformed(evt);
            }
        });
        jmn_research.add(jmi_exit);

        jmain_menu.add(jmn_research);

        jmn_view.setText("Вид");

        jmic_graph_viewer.setText("Обозреватель графиков");
        jmic_graph_viewer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmic_graph_viewerActionPerformed(evt);
            }
        });
        jmn_view.add(jmic_graph_viewer);

        jmain_menu.add(jmn_view);

        jmnu_experiment.setText("Эксперимент");

        jmi_open_exp.setText("Открыть");
        jmi_open_exp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_open_expActionPerformed(evt);
            }
        });
        jmnu_experiment.add(jmi_open_exp);

        jmi_save_exp.setText("Сохранить");
        jmi_save_exp.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_save_expActionPerformed(evt);
            }
        });
        jmnu_experiment.add(jmi_save_exp);

        jmain_menu.add(jmnu_experiment);

        jmnu_service.setText("Сервис");

        jmi_calib_sensors.setText("Калибровка");
        jmi_calib_sensors.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_calib_sensorsActionPerformed(evt);
            }
        });
        jmnu_service.add(jmi_calib_sensors);

        jmi_hand_pos.setText("Ручное позиционирование");
        jmi_hand_pos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_hand_posActionPerformed(evt);
            }
        });
        jmnu_service.add(jmi_hand_pos);

        jmi_forecast.setText("Прогнозирование");
        jmi_forecast.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmi_forecastActionPerformed(evt);
            }
        });
        jmnu_service.add(jmi_forecast);

        jmain_menu.add(jmnu_service);

        setJMenuBar(jmain_menu);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jmi_runresearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_runresearchActionPerformed
        startResearch();
    }//GEN-LAST:event_jmi_runresearchActionPerformed

    private void jmi_editresearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_editresearchActionPerformed
        editResearch();
    }//GEN-LAST:event_jmi_editresearchActionPerformed

    private void jmic_graph_viewerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmic_graph_viewerActionPerformed
        graph_viewer.setVisible(jmic_graph_viewer.getState());
    }//GEN-LAST:event_jmic_graph_viewerActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        Configurator.getConf().saveConfig();
        System.exit(0);
    }//GEN-LAST:event_formWindowClosing

    private void jmi_open_expActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_open_expActionPerformed
        SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        new LoadExpFrame(sl_exp_cont, exp_c).setVisible(true);
                    }
                });
        
    }//GEN-LAST:event_jmi_open_expActionPerformed

    private void jmi_save_expActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_save_expActionPerformed
        if (viewer_exps.getSelectedExp() != null) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        new SaveExpFrame(viewer_exps.getSelectedExp(),sl_exp_cont)
                                .setVisible(true);
                    }
                });
            }
    }//GEN-LAST:event_jmi_save_expActionPerformed

    private void jmi_exitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_exitActionPerformed
        System.exit(0);
    }//GEN-LAST:event_jmi_exitActionPerformed

    private void jmi_create_researchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_create_researchActionPerformed
        createResearch();
    }//GEN-LAST:event_jmi_create_researchActionPerformed

    private void jmi_start_researchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_start_researchActionPerformed
        startResearch();
    }//GEN-LAST:event_jmi_start_researchActionPerformed

    private void jmi_calib_sensorsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_calib_sensorsActionPerformed
        //if(calib_frame==null){
            calib_frame = new CalibFrame(data_tract);
            calib_frame.setVisible(true);
        /*}else{
            calib_frame.setVisible(true);
        }*/
    }//GEN-LAST:event_jmi_calib_sensorsActionPerformed

    private void jmi_hand_posActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_hand_posActionPerformed
        //if(moving_frame==null){
            moving_frame = new MovingFrame(data_tract);
            moving_frame.setVisible(true);
        /*}else{
            moving_frame.setVisible(true);
        }*/
    }//GEN-LAST:event_jmi_hand_posActionPerformed

    private void jmi_forecastActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jmi_forecastActionPerformed
        forecast_frame = new ForecastFrame(data_tract, exp_c);
        forecast_frame.setVisible(true);
    }//GEN-LAST:event_jmi_forecastActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(MainFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        new MainFrame().setVisible(true);

    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JPopupMenu.Separator jSeparator1;
    private javax.swing.JTree jTree1;
    private javax.swing.JList jl_research;
    private javax.swing.JMenuBar jmain_menu;
    private javax.swing.JMenuItem jmi_calib_sensors;
    private javax.swing.JMenuItem jmi_create_research;
    private javax.swing.JMenuItem jmi_editresearch;
    private javax.swing.JMenuItem jmi_exit;
    private javax.swing.JMenuItem jmi_forecast;
    private javax.swing.JMenuItem jmi_hand_pos;
    private javax.swing.JMenuItem jmi_open_exp;
    private javax.swing.JMenuItem jmi_runresearch;
    private javax.swing.JMenuItem jmi_save_exp;
    private javax.swing.JMenuItem jmi_start_research;
    private javax.swing.JCheckBoxMenuItem jmic_graph_viewer;
    private javax.swing.JMenu jmn_research;
    private javax.swing.JMenu jmn_view;
    private javax.swing.JMenu jmnu_experiment;
    private javax.swing.JMenu jmnu_service;
    private javax.swing.JPopupMenu jppm_research;
    // End of variables declaration//GEN-END:variables
}
